home *** CD-ROM | disk | FTP | other *** search
- Path: sundog.tiac.net!usenet
- From: page@tiac.net (Chris Page)
- Newsgroups: comp.lang.c++
- Subject: Re: Constructor Exceptions
- Date: Wed, 03 Jan 1996 15:05:55 GMT
- Organization: The Internet Access Company
- Message-ID: <4ce68n$8u4@sundog.tiac.net>
- References: <4bud9g$pv5@oxy.rust.net> <4cbhcl$kst@dawn.mmm.com>
- NNTP-Posting-Host: page.tiac.net
- X-Newsreader: Forte Free Agent 1.0.82
-
- kjhopps@mmm.com (Kevin J Hopps) wrote:
-
- :Paul Gunn (pgunn@mail.cbf.com) wrote:
-
- :> I use Microsoft Visual C++, and have been gradually making use of
- :> exceptions in my code. I'm interested in using exceptions in my
- :> constructor code, but according to a MS article, when an exception is
- :> thrown from a constructor on a heap object, the memory will not be
- :> freed.
-
- :> Is this behavior parculiar to the Microsoft implementation or is it
- :> generally the case?
-
- :It is not generally the case. Compilers that adhere to the standard
- :will produce code that does not leak memory in this way.
-
- Sure, they'll clean up 'this', but the programmer is responsible for
- any and all heap memory allocated within the body of constructor.
-
- For example,
-
- class Foo {
- public:
- Foo(int initNum) : mNum(initNum), // # 0
- m1Ptr(new Part1), // # 1
- m2Ptr(new Part2) {}; // # 2
- private:
- int mNum;
- Part1 *m1Ptr;
- Part2 *m2Ptr;
- };
-
- Let's assume a Foo is created from the heap:
-
- Foo *myFooPtr = new Foo(12);
-
- And an exception is thrown (xalloc) when 'new Part2' (#2) fails.
-
- The storage allocated for Foo which is sizeof(Foo) is cleaned up. The
- memory allocated on line #2 using 'new Part1' is a leaked.
-
-
- The solution to this problem is to use the "resource allocation is
- class initialization" technique, which has been discussed in the news
- group many time before.
-
- -Chris
-
-
-
-